package threading;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.Semaphore;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Microsoft
 * Date: 2023-07-21
 * Time: 16:14
 */
public class ThreadDemo27 {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(4);
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("申请资源");
                    semaphore.acquire();
                    System.out.println("我获取到资源了");
                    Thread.sleep(1000);
                    System.out.println("我释放资源了");
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        for (int i = 0; i < 20; i++) {
            Thread t = new Thread(runnable);
            t.start();
        }
    }
}







//
//    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        //这只是创建个任务
//        Callable<Integer> callable = new Callable<Integer>() {//Callable接口的泛型参数写什么是和call方法的返回值类型一致的
//            @Override
//            public Integer call() throws Exception {
//                int sum = 0;
//                for (int i = 0; i < 11; i++) {
//                    sum += i;
//                }
//                return sum;
//            }
//        };
//
//        //还需要找个线程来完成任务
//        //Thread不能直接接受callable，需要包装一层
//        FutureTask<Integer> futureTask = new FutureTask<>(callable);
//        Thread t = new Thread(futureTask);
//        t.start();
//
//        System.out.println(futureTask.get());//futureTask中包含了一个get方法，就是用来取callable结果的方法。
//
//    }
